package org.unique.support.orm.connection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import javax.sql.DataSource;

import org.unique.Const;
import org.unique.commons.io.PropUtil;
import org.unique.ioc.AbstractBeanFactory;
import org.unique.ioc.impl.SingleBean;
import org.unique.support.orm.ds.DataSourceFactory;
import org.unique.support.orm.ds.JdbcDataSource;
import org.unique.support.orm.exception.DataSourceException;

/**
 * 数据源连接管理器
 * @author biezhi
 * @version 1.0
 */
public final class ConnectionManager {

	private static DataSource dataSource;
	
	private static final Map<String, String> dbConfig = PropUtil.getPropertyMap(Const.getConfig("unique.db.config"));
	
	private static final AbstractBeanFactory beanFactory = new SingleBean();
	
	private ConnectionManager() {
	}
	
	static{
		String poolType = Const.getConfig("unique.db.pooltype");
		if(poolType.equalsIgnoreCase("jdbc")){
			dataSource = getJdbcDataSource();
		} else{
			Object dsFactoryObj = beanFactory.getBean(DataSourceFactory.class);
			if(null != dsFactoryObj && dsFactoryObj instanceof DataSourceFactory){
				dataSource = ((DataSourceFactory) dsFactoryObj).getDataSource();
				if(null == dataSource){
					throw new DataSourceException("数据源初始化失败！");
				}
			}
		}
	}
	
	/**
	 * 提供动态注入datasource
	 * @param dataSource_
	 */
	public static void setDataSource(DataSource dataSource_){
		dataSource = dataSource_;
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	/**
	 * 获取jdbc数据源
	 * @return JdbcDataSource
	 */
	private static DataSource getJdbcDataSource(){
		String url = dbConfig.get("jdbc.url");
		String driver = dbConfig.get("jdbc.driver");
		String username = dbConfig.get("jdbc.username");
		String password = dbConfig.get("jdbc.password");
		dataSource = new JdbcDataSource(url, driver, username, password);
		return dataSource;
	}
	
	/**
	 * 获取数据库链接
	 * @return connection对象
	 */
	public static Connection getConnection() {
		try {
			if(null != dataSource){
				return SingleThreadConnectionHolder.getConnection(dataSource);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return null;
	}

}
